﻿package gui;

import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JButton;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTable;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.util.Date;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import XML.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class GUI extends JFrame {
	private static final long serialVersionUID = -6825444160544909790L;
	private JPanel contentPane;
	private ListTaskTableModel model;
	private JTable tableTask;
	private JButton deleteTask;
	private JButton editTask;
	private JFileChooser openFileDialog;
        private static UIManager.LookAndFeelInfo[] names=UIManager.getInstalledLookAndFeels(); //!для задания стиля отображения - все в стиле Windows NT
        
        private DataXmlList journal;//!ссылка на файл xml
        private Object mainThread;//!ссылка на главный поток в программе, который запускает необходимые задачи

	public GUI(DataXmlList XML,Object th) {
                //setVisible(true);
                journal=XML;
                mainThread=th;
                
                //!меняем стиль
                try {
                    UIManager.setLookAndFeel(names[3].getClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(NewTaskWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
                SwingUtilities.updateComponentTreeUI(this);
                
                
		//setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Dmitry\\workspaceClearJava\\test\\src\\resource\\icon.png"));
		setTitle("Task Manager 0.1");
		setResizable(true);
		//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                //!закрытие с сохранением задач
                addWindowListener(new WindowAdapter(){
                    public void windowClosing(java.awt.event.WindowEvent we){
                        try {
                            journal.save();
                            System.exit(0);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, "Невозможно сохранить файл", "Ошибка", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });
		setBounds(10, 10, 480, 550);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);

		JMenuItem mntmNewFile = new JMenuItem("New File");
		mnFile.add(mntmNewFile);

		JMenuItem mntmLoadFile = new JMenuItem("Load file");
		mntmLoadFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				menuLoadActionPerformed();
			}
		});
		mnFile.add(mntmLoadFile);
		
		openFileDialog = new JFileChooser();

		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);

		JMenuItem mntmAbout = new JMenuItem("About");
		mntmAbout.setSelected(true);
		mnHelp.add(mntmAbout);

		JMenuItem mntmHelp = new JMenuItem("Help");
		mnHelp.add(mntmHelp);
		contentPane = new JPanel();
		contentPane.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(java.awt.event.MouseEvent e) {
				tableTask.getSelectionModel().clearSelection();
				deleteTask.setEnabled(false);
				editTask.setEnabled(false);
				
			}
		});
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		

		JButton addTask = new JButton("Add Task");
		addTask.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				clickButtonAddTask();
			}
		});

		deleteTask = new JButton("Delete Task");
		deleteTask.setEnabled(false);
		deleteTask.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				clickButtonDeleteTask();
			}
		});
		// JScrollPane scrolTableTask = new JScrollPane();
		// DefaultTableModel mod = new DefaultTableModel();
                
                model = new ListTaskTableModel(this, journal);

		JScrollPane scrollPaneTable = new JScrollPane();
		
		editTask = new JButton("Edit Task");
		editTask.setEnabled(false);
		editTask.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPaneTable, GroupLayout.PREFERRED_SIZE, 269, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(editTask)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(deleteTask)
							.addPreferredGap(ComponentPlacement.RELATED, 193, Short.MAX_VALUE)
							.addComponent(addTask)))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPaneTable, 400, 400, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(editTask)
						.addComponent(deleteTask)
						.addComponent(addTask))
					.addContainerGap())
		);
		tableTask = new JTable();
                tableTask.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		tableTask.setModel(model);
		System.out.println(tableTask.getMousePosition());
		//tableTask.getColumnModel().getColumn(0).setMinWidth(60);
		/*
		tableTask.getColumnModel().getColumn(0).setPreferredWidth(10);
		tableTask.getColumnModel().getColumn(0).setMinWidth(10);
		tableTask.getColumnModel().getColumn(0).setMaxWidth(10);

		tableTask.getColumnModel().getColumn(1).setPreferredWidth(70);
		tableTask.getColumnModel().getColumn(1).setMinWidth(70);
		tableTask.getColumnModel().getColumn(1).setMaxWidth(70);

		tableTask.getColumnModel().getColumn(2).setPreferredWidth(40);
		tableTask.getColumnModel().getColumn(2).setMinWidth(40);
		tableTask.getColumnModel().getColumn(2).setMaxWidth(40);*/
		tableTask.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
	
			public void valueChanged(ListSelectionEvent e) {
				// TODO Auto-generated method stub
				deleteTask.setEnabled(true);
				//editTask.setEnabled(true); !пока нет такой функции
			}
                        public void FocusLost(java.awt.event.FocusEvent evt){//!невозможность нажатия на кнопки при уходе мышки
                                deleteTask.setEnabled(false);
				editTask.setEnabled(false);
                        }
		});
		model.fireTableStructureChanged();

		scrollPaneTable.setViewportView(tableTask);
		contentPane.setLayout(gl_contentPane);
	}

	private void clickButtonAddTask() {
		new NewTaskWindow(journal,mainThread,model);
                
	}
	private void clickButtonDeleteTask() {
		model.getList().remove(tableTask.getSelectedRow());
		model.fireTableStructureChanged();
                
                //!теряется фокус мышки
                deleteTask.setEnabled(false);
		editTask.setEnabled(false);
	}
	private void menuLoadActionPerformed () {
		int file = openFileDialog.showDialog(this, "Select application");


	}
}
